package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号码
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号码不正确");
        }
        //2.通过，使用hutool生成验证码
        String code = RandomUtil.randomNumbers(6);
        //3.保存验证码到session
        session.setAttribute("code",code);
        //4.发送验证码(第三方工具，我们直接打印日志)
        log.debug("发送的验证码是：{}",code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        //1.手机号校验
        if(RegexUtils.isPhoneInvalid(phone)){
            //校验失败
            return Result.fail("手机号码有误!");
        }
        String Cachecode = loginForm.getCode();
        String code = (String)session.getAttribute("code");
        //2.验证码校验
        if(Cachecode == null || !code.equals(Cachecode)){
            //校验失败
            return Result.fail("验证码有误！");
        }
        //3.全部验证通过，根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //4.判断用户是否存在
        if(user == null){
            user = new User();
            user.setPhone(phone);
            user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomNumbers(6));
            //不存在，则保存用户
            save(user);
        }
        //5.保存用户到session（隐藏敏感信息）
        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        //session.setAttribute("user",user);//未隐藏敏感信息
        return Result.ok();
    }
}
